<?php
define('TX', 3);
set_time_limit(0);
class MiYouQuanAction extends Action {
	//获取密友圈密友列表
	public function getQuanList($name=null,$order="mi.updateTime", $orderBy="desc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("miyouquan");
		$quanUser = M("quan_user");
		$Model_IndMediaInfo = M('ind_media_info');
		Session::switchCustomer($cid);
		$user = M("user");
		//明天看一下现在还没有主公姓名
		$where['mi.cId'] = array("eq",$cid);
		$where["mi.name"] = array("like", "%".$name."%");
		$arr = $MiModel
			->field("mi.*,mi.buyOrderCount as orderCount,mi.buyOrderPrice as orderPrice,mi.id as id")
			->alias("mi")
			->where($where)
			->order("$order $orderBy")->limit("$start, $limit")->select();
		$url = $this->getH5ServerPath();
		if ($arr) {
			//循环取主公id
			foreach ($arr as $key=>$value){
				$arr[$key]['communityUrl'] =$url.'/spa/index.html#/quan?customerId='.$cid.'&scope=60&params=%7B%22qId%22%3A'.$value['id'].',%22community%22%3A1%7D';
				$where_lord['identity'] = 0;
				$where_lord['qid'] = $value['id'];
				$where_lord['deleted'] = 0;
				$lordId = $quanUser->where($where_lord)->getField("uid");
				if ($lordId){
					$where_lord_info['uid'] = $lordId;
					$where_lord_info['qid'] = $value['id'];
					$where_lord_info['deleted'] = 0;
					$lordName = $quanUser->where($where_lord_info)->getField("nickName");
					$arr[$key]['lordId'] = $lordId;
					$arr[$key]['lordName'] = $lordName;
				}else{
					$arr[$key]['lordId'] = '';
					$arr[$key]['lordName'] = '';
				}
				$arr[$key]['miUCount'] = $quanUser->where(['qid' => $value['id'],'deleted' => 0])->count();
			}
			$count = $MiModel
				->field("*,mi.id as id")
				->alias("mi")
				->where($where)
				->count();
			//	echo $MiModel->getLastSql();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}


	}

	/**
	 * 获取配cofig.php连接地址
	 * @return config中的连接
	 */
	public function getH5ServerPath(){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$Model_IndMediaInfo = M('ind_media_info');
		Session::switchCustomer($cid);

		//获取平台默认公众号信息
		$mediaInfo = $Model_IndMediaInfo->where(['cid' => $cid, 'isDefault' => 1])->field('appid,mode')->find();
		if($mediaInfo['mode'] == 1){
			$url ='http://' . $mediaInfo['appid'] . '.'.C('NEWSERVER_NAME');
		}else{
			$url =C('SERVER_NAME');
		}
		return $url;
	}
	/*public function deleteQuan($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("miyouquan");
		Session::switchCustomer($cid);


		$result = $MiModel->where("id=$id")->delete();
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}*/


	//新建密友圈  LP已修改
	public function addQuan($name = NULL,$logo = NULL,$miMaxCount = NULL,$miAward = NULL,$lordAward=null,
							$articleId=0,$bgImgUrl="",$registerStatus=0,$joinType=0,$config=NULL,$parentRefereeAward=null,
							$refereeAward=null,$refereeImg=null,$joinContent=null,$joinPid=null,
							$shareTitle=null,$shareImg=null,$description=null,$payContent=null,$json=null,$mallId=null,$staffJoin=null,$signSaleSource=null,$contactEnable=null,$contactInherit=null,$vid=null,$isSynchro=0,$cutRank = 3 ,$onlyCutReferee = 0, $joinQualType = 1, $isOfflinePay = 0, $rankInfo = null,$joinQuanUserAward=null,$joinQuanMiAward=null,$joinQuanRefereeAward=null,$joinQuanParentRefereeAward=null, $isShowRank = 0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$time = date("Y-m-d H:i:s");


		//添加密友圈，并获取插入成功的圈id
		$MiModel = M("miyouquan");
		$MiQuanRankModel = M("miyouquan_setting_rank");
		$data["name"] = $name;
		$data["logo"] = $logo;
		$data["miMaxCount"] = $miMaxCount;
		//$data["lordAward"] = $lordAward;
		$data["miAward"] = $miAward;
		$data['staffJoin'] = $staffJoin;
		$data['signSaleSource'] = $signSaleSource;
		$data['contactEnable'] = $contactEnable;
		$data['contactInherit'] = $contactInherit;
		$data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["articleId"]=$articleId;
		$data["bgImgUrl"]=$bgImgUrl;
		$data["registerStatus"] = $registerStatus;
		$data["joinType"] = $joinType;
		$data["config"] = $config;
		$data["refereeAward"]=$refereeAward;
		$data["refereeImg"]=$refereeImg;
		$data["joinContent"]=$joinContent;
		$data["joinPid"]=$joinPid;
		$data["shareTitle"]=$shareTitle;
		$data["shareImg"]=$shareImg;
		$data["description"]=$description;
		$data['parentRefereeAward']=$parentRefereeAward;
		$data["payContent"]=$payContent;
		$data['json']=$json;
		//$data["mallId"]=$mallId;
		$data["cId"]=$cid;
		$data["isSynchro"]=$isSynchro;
		$data["cutRank"]=$cutRank;
		$data["onlyCutReferee"]=$onlyCutReferee;
		$data["joinQualType"]=$joinQualType;
		$data["isOfflinePay"]=$isOfflinePay;
        $data["joinQuanUserAward"]=$joinQuanUserAward;
        $data["joinQuanMiAward"]=$joinQuanMiAward;
        $data["joinQuanRefereeAward"]=$joinQuanRefereeAward;
        $data["joinQuanParentRefereeAward"]=$joinQuanParentRefereeAward;
        $data["isShowRank"]=$isShowRank;
		if($vid != null){
			$data["vid"]=$vid;
			$data["bingVendorTime"]=date('Y-m-d H:i:s');
		}




		$micondition['name'] = $name;
		//$micondition['account'] = 'thinkphp';
		//$micondition['_logic'] = 'OR';
		$findresult = $MiModel->where($micondition)->find();
		if($findresult){
			Output::instance()->resultCode(code_sql_error,"密友圈已存在！！");
			exit;
		}else{
			$result = $MiModel->add($data);
		}
		if(!empty($rankInfo)){
			$rankInfo = json_decode($rankInfo, true);
			foreach($rankInfo  as $key => $value){
				$rankData[$key]['cid'] = $cid;
				$rankData[$key]['qid'] = $result;
				$rankData[$key]['rankName'] = $value['rankName'];
				$rankData[$key]['miAward'] = $value['miAward'];
				$rankData[$key]['refereeAward'] = $value['refereeAward'];
				$rankData[$key]['parentRefereeAward'] = $value['parentRefereeAward'];
			}
			$MiQuanRankModel->addAll($rankData);
		}


		//添加所有用户表
		// $MiUserModel = M("all_user");
		// $userData["fullName"]=$lordname;
		// $userData["phone"]=$lordphone;

		// $miUsercondition['fullName'] = $lordname;
		// $miUsercondition['phone'] = $lordphone;
		// $miUsercondition['_logic'] = 'OR';
		//       $findUserresult = $MiUserModel->where($miUsercondition)->find();
		//       if($findUserresult){
		//       	// Output::instance()->resultCode(code_sql_error,"姓名或手机号已存在！");
		//       	// exit;
		//           $userResult=$findUserresult['id'];
		//       }else{
		//       	$userResult = $MiUserModel->add($userData);

		//       }


		// //添加密友圈用户表
		// $MiQuanUserModel = M("quan_user");
		// $quaUserData["qid"]=$result;
		// $quaUserData["uid"]=$userResult;
		// $quaUserData["name"]=$lordname;
		// $quaUserData["identity"]=0;
		// $quaUserData["status"]=1;
		// $quaUserData["createTime"]=$time;
		// $quanUserResult = $MiQuanUserModel->add($quaUserData);

		Session::switchCustomer($cid);
		if ($result) {
		    $LastSql = $MiQuanRankModel->getLastSql();
            R('Log/add',array('marketing','','营销圈',op_add,$LastSql,'添加营销圈' . $name));
			$data["id"] = $result;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}





	public function getQuanById($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("miyouquan");
		$MiVendorModel = M("mivendor");
		$MiQuanRankModel = M('miyouquan_setting_rank');
		Session::switchCustomer($cid);

		$condition["mi.id"] = array("eq",$id);
		$mi = $MiModel->alias("mi")
			->join("left join wx_module_product b on mi.joinPid=b.id")
			->join("left join wx_mivendor c on mi.vid=c.id")
			// ->join("wx_quan_user as quser on mi.id=quser.qid")
			// ->join("wx_".$cid."_web_page as w on w.id=mi.articleId")
			// ->join("wx_all_user as auser on auser.id=quser.uid")
			->field("mi.*,b.name as joinProName,c.name as vendorName")
			->where($condition)->find();
		if($mi['json']){
			$mi['json']=json_decode($mi['json'],true);

		}
		if($mi['config']){
			$mi['config']=json_decode($mi['config'],true);

		}
		$rankInfo = $MiQuanRankModel->where(['qid' => $id])->select();
		empty($rankInfo) ? $rankInfo = [] : '';
		$mi['rankInfo'] = $rankInfo;
		if($mi['vid']){
			$mi['supplieModule']= $MiVendorModel->where(['id' => $mi['vid']])->getField('supplieModule');
		}
		$mi['communityUrl'] ='http://'.C("PLANT_APPID").'.'.C('NEWSERVER_NAME').'/spa/index.html#/quan?customerId='.$cid.'&params=%7B%22qId%22%3A'.$id.',%22community%22%3A1%7D';
//		echo $MiModel->getLastSql();
		if ($mi) {
			Output::instance()->object($mi);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}

	public function upgradeTeam($uid,$qid,$teamId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$quanTeam = M("quan_team");
		$quanUser = M("quan_user");
		$orderModel = M("module_product_order");
		Session::switchCustomer($cid);
		$nowTime = date("Y-m-1 H:i:s");
		$teamInfo = $quanTeam->where("id=$teamId")->find();
		$orderInfo = $orderModel->where("qId=$qid and miUid=$uid and status='ok' and completionTime>'$nowTime'")->field("sum(price) as sales,count(id) as orders")->find();
		if(!$orderInfo['orders']){
			$orderInfo['orders']=0;
		}
		if(!$orderInfo['sales']){
			$orderInfo['sales'] = 0;
		}
		$quanUser->startTrans();
		$data['cid']=$cid;
		$data['quanId']=$qid;
		$data['teamLeader']=$uid;
		$data["parentTeam"]=$teamId;
		$data["createTime"] = date("Y-m-d H:i:s");
		$data["updateTime"] = date("Y-m-d H:i:s");
		$data['totalPerson']=1;
		$data['totalSales']=$orderInfo['sales'];
		$data['totalOrder']=$orderInfo['orders'];
		$newTeamId = $quanTeam->add($data);
		$where["uid"]=array("eq",$uid);
		$where["qid"]=array("eq",$qid);
		$quanResult = $quanUser->where($where)->setfield(["teamId"=>$newTeamId,"joinTeamTime"=>date("Y-m-d H:i:s")]);
		if($quanResult===false){
			$quanUser->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		if($teamId){
			$teamData['totalPerson']=$teamInfo['totalPerson']-1;
			$teamData['totalSales']=$teamInfo['totalSales']-$orderInfo['sales'];
			$teamData['totalOrder']=$teamInfo['totalOrder']-$orderInfo['orders'];
			$quanTeam->where("id=$teamId")->save($teamData);
		}
		if($quanResult===false){
			$quanUser->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}else{
			$quanUser->commit();
			Output::instance()->resultCode();
		}
	}
	public function cancelTeam($teamId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$quanTeam = M("quan_team");
		$quanUser = M("quan_user");
		Session::switchCustomer($cid);
		$quanUser->startTrans();
		$teamWhere["id"]=array("eq",$teamId);
		$data["deleted"]=1;
		$data["updateTime"]=date("Y-m-d H:i:s");
		$teamResult = $quanTeam->where($teamWhere)->save($data);
		$userWhere['teamId']=array("eq",$teamId);
		$quanResult = $quanUser->where($userWhere)->setField("teamId",NULL);
		if($teamResult===false||$quanResult===false){
			$quanUser->rollback();
			Output::instance()->resultCode(code_sql_error);
		}else{
			$quanUser->commit();
			Output::instance()->resultCode();
		}
	}

	//修改密友圈信息  LP已修改
	public function updateQuan($id,$name = NULL,$logo = NULL,$miMaxCount = NULL,$miAward = NULL,
							   $articleId=0,$bgImgUrl="",$updateQRImg=0,$registerStatus=0,$joinType=0,$config=NULL,
							   $refereeAward=null,$parentRefereeAward=null,$refereeImg=null,$joinContent=null,$joinPid=null,$payContent=null,
							   $shareTitle=null,$shareImg=null,$description=null,$json=null,$mallId=null,$staffJoin=null,$signSaleSource=null,$contactEnable=null,$contactInherit=null,$vid=null,$isSynchro=0,$cutRank = 3 ,$onlyCutReferee = 0, $joinQualType = 1, $isOfflinePay = 0, $rankInfo = null,$joinQuanUserAward=null,$joinQuanMiAward=null,$joinQuanRefereeAward=null,$joinQuanParentRefereeAward=null, $isShowRank = 0){

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("miyouquan");
		$quanUserModel=M('quan_user');
		$MiQuanRankModel = M('miyouquan_setting_rank');
		$time = date("Y-m-d H:i:s");

		$time = date("Y-m-d H:i:s");
		$data["name"] = $name;
		$data["logo"] = $logo;
		$data["miMaxCount"] = $miMaxCount;
		$data["miAward"] = $miAward;
		$data['staffJoin'] = $staffJoin;
		$data['signSaleSource'] = $signSaleSource;
		$data['contactEnable'] = $contactEnable;
		$data['contactInherit'] = $contactInherit;
		# $data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["articleId"]=$articleId;
		$data["bgImgUrl"]=$bgImgUrl;
		$data["registerStatus"] = $registerStatus;
		$data["joinType"]=$joinType;
		$data["config"]=$config;
		$data["refereeAward"]=$refereeAward;
		$data["parentRefereeAward"]=$parentRefereeAward;
		$data["refereeImg"]=$refereeImg;
		$data["joinContent"]=$joinContent;
		$data["joinPid"]=$joinPid;
		$data["shareTitle"]=$shareTitle;
		$data["shareImg"]=$shareImg;
		$data["description"]=$description;
		$data["payContent"]=$payContent;
		$data["json"]=$json;
		$data["isSynchro"]=$isSynchro;
		$data["cutRank"]=$cutRank;
		$data["onlyCutReferee"]=$onlyCutReferee;
		$data["joinQualType"]=$joinQualType;
		$data["isOfflinePay"]=$isOfflinePay;
        $data["joinQuanUserAward"]=$joinQuanUserAward;
        $data["joinQuanMiAward"]=$joinQuanMiAward;
        $data["joinQuanRefereeAward"]=$joinQuanRefereeAward;
        $data["joinQuanParentRefereeAward"]=$joinQuanParentRefereeAward;
        $data["isShowRank"]=$isShowRank;
		if($vid != null){
			$data["vid"]=$vid;
			$data["bingVendorTime"]=date('Y-m-d H:i:s');
		}
		if($updateQRImg==1) {
			$data["qrCodeImg"]="";
		}
		$result = $MiModel->where("id=$id")->save($data);

		$rankInfo = json_decode($rankInfo, true);
		$rankId = array_column($rankInfo,'id');
		empty($rankId) ? '' : $delWhere['id'] = array('not in', $rankId);
		$delWhere['qid'] = array('eq', $id);
		$delRankIds = $MiQuanRankModel->where($delWhere)->getField('id', true);
		if(!empty($delRankIds)){
			$delRankIds = implode(',',$delRankIds);
			$delRankWhere['rankId'] = array('in', $delRankIds);
			$quanUserModel->where($delRankWhere)->setField('rankId', 0);
		}

		$MiQuanRankModel->where($delWhere)->delete();
		if(!empty($rankInfo)){
			foreach($rankInfo  as $key => $value){
				$rankData['cid'] = $cid;
				$rankData['qid'] = $id;
				$rankData['rankName'] = $value['rankName'];
				$rankData['miAward'] = $value['miAward'];
				$rankData['refereeAward'] = $value['refereeAward'];
				$rankData['parentRefereeAward'] = $value['parentRefereeAward'];
				if(isset($value['id'])){
					$MiQuanRankModel->where(['id' => $value['id']])->save($rankData);
				}else{
					$MiQuanRankModel->add($rankData);
				}
			}

		}

		Session::switchCustomer($cid);
		if ($result !== false) {
			$data["id"] = $id;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}




//密友圈用户相关操作

	public function getQuanUserList($qid,$fullName=null,$order="quser.createTime", $orderBy="desc", $start = 0, $limit = 25,$express=0,$status='no',$saleSource='') {

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("quan_user");
		$quanModel = M("miyouquan");
		Session::switchCustomer($cid);
		if($fullName){
            $condition['auser.fullName|e.nickname'] = array("like", "%".$fullName."%");
		}
		if($status !== 'no'){
			$condition["quser.status"] = $status;
		}
		if ($saleSource == 'no'){
            $condition["quser.isSaleSource"] = 0;
        }else if ($saleSource == 'yes'){
            $condition["quser.isSaleSource"] = 1;
        }
		$condition["quser.deleted"] = array("eq",0);
		$condition["quser.qid"] = array("eq",$qid);
		if(!$express){
			$arr = $MiModel->alias("quser")
				->field("rank.rankName,quser.*,e.nickname as uNickName, e.headimgurl as uHeadImgUrl,c.nickname as rNickName,c.headimgurl as rHeadImgUrl,auser.phone,auser.fullName,d.teamLeader")
				->join("wx_".$cid."_user_weixin_info c on quser.refereeUid = c.userId")
				->join("wx_".$cid."_user_weixin_info e on quser.uid = e.userId")
				->join("wx_".$cid."_user as auser on auser.id=quser.uid")
				->join("wx_quan_team d on quser.teamId=d.id and d.deleted=0")
				->join("wx_miyouquan_setting_rank as rank on quser.rankId = rank.id")
				->where($condition)->order("$order $orderBy")
				->group("quser.id")
				->limit("$start, $limit")->select();

			foreach ($arr as $key => $value) {
				$arr[$key]['miCoins'] = round($value['miCoins'],2);
                $StatisData = $this->StatisData($cid,$qid,$arr[$key]['uid'],1);
                $arr[$key]['shareCount'] =  $StatisData['shareCount'];
			}
			if ($arr) {
				$count = $MiModel->alias("quser")->field("*,quser.createTime as createTime,auser.id as id")->join("wx_".$cid."_user as auser on auser.id=quser.uid")->where($condition)->join("wx_".$cid."_user_weixin_info e on quser.uid = e.userId")->count();
				$result=$quanModel->where('id=' . $qid)->find();
				Output::instance()->object(['results' => $arr, 'total' => $count, 'quanInfo' => $result]);
			} else {
				Output::instance()->resultCode(code_success);
			}
		}else{
            if(empty($status)){
                unset($condition['quser.status']);
            }
            $arr = $MiModel->alias("quser")
                ->field("auser.fullName,quser.status,auser.phone,quser.miCoins,c.fullName as rNickName,quser.createTime,d.fullName as saleSource")
                ->join("wx_".$cid."_user c on quser.refereeUid = c.id")
                ->join("wx_".$cid."_user d on quser.saleSource = d.id")
                ->join("wx_".$cid."_user_weixin_info e on quser.uid = e.userId")
                ->join("wx_".$cid."_user as auser on auser.id=quser.uid")
                ->where($condition)->order("$order $orderBy")
                ->group("quser.id")
                ->select();
			$field = array(
			  'A' => array('fullName', '姓名'),
			  'B' => array('status', '审核状态'),
			  'C' => array('phone', '手机'),
			  'D' => array('miCoins', '账号余额'),
//			  'E' => array('createTime', '创建时间'),
              'E' => array('rNickName','推荐人姓名'),
              'F' => array('saleSource', '销售员姓名'),

            );
			foreach ($arr as $k1 => $v1) {
//                $StatisData = $this->StatisData($cid,$qid,$arr[$k1]['uid'],1);
//                $arr[$k1]['shareCount'] =  $StatisData['shareCount'];
				if($v1['status']==1){
					$v1['status'] = '审核通过';
				}else{
					$v1['status'] = '等待审核';
				}
				$data[] = $v1;
			}
			Output::instance()->phpExcelList($field, $data,'密友列表'.date("Y-m-d H:i:s"));
		}



	}

	public function changeUserIden($oldQid,$qid,$uid,$type=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		Log::write($qid);
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("quan_user");
		Session::switchCustomer($cid);
		$condition["qid"] = array("eq", $oldQid);
		$condition["uid"] = array("eq",$uid);
		$condition["deleted"] = 0;
		$isExist=$MiModel->where("qid=$qid and identity=0 and deleted=0")->find();
		$arr = $MiModel->where($condition)->find();
		if ($arr) {
			if($arr["identity"]==1) {
				$updateData["identity"]=0;
				$updateData["status"]=1;
				$updateData["deleted"]=0;
				$updateData["qid"]=$qid;
				if($isExist && count($isExist) > 0){
					if ($type) {
						$return['code'] = '1';
						$return['msg'] = '本圈中已经存在主公，升级失败！';
						return $return;
					}else{
						Output::instance()->resultCode(1,"本圈中已经存在主公，升级失败！");
						return;
					}


				}
				$MiModel->startTrans();
				//更新账户信息
				$success1=$MiModel->query("update wx_mitask_user set qId=".$qid."  where uid=".$uid);
				Log::write($MiModel->getlastsql());
				$success2=$MiModel->query("update wx_miaccount_friend set quanId=".$qid."  where uid=".$uid);
				Log::write($MiModel->getlastsql());
				$success3=$MiModel->query("update wx_module_product_order set qId=".$qid."  where miUid=".$uid." and qId=".$oldQid);
				Log::write($MiModel->getlastsql());
				$success4=$MiModel->where($condition)->save($updateData);
				if($success1!==false && $success2!==false && $success3!==false && $success4!==false) {
					$MiModel->commit();
					if ($type) {
						$return['code'] = 0;
						$return['msg'] = 'ok';
						return $return;
					}else{
						Output::instance()->resultCode(code_success);
						return;
					}

				}
			} else {
				$updateData["identity"]=1;
				$success4=$MiModel->where($condition)->save($updateData);
				if ($type) {
					$return['code'] = 0;
					$return['msg'] = 'ok';
					return $return;
				}else{
					Output::instance()->resultCode(code_success);
					return;
				}
			}
		} else {
			$MiModel->rollback();
			if ($type) {
				$return['code'] = 505;
				$return['msg'] = '数据读写错误';
				return $return;
			}else{
				Output::instance()->resultCode(code_success);
				return;
			}
		}
	}

	/**
	 * 重新统计好友数 及 注册好友数数据
	 * @param $uids  统计人id(多个用逗号拼接)
	 * @param $qid	  圈id
	 */
	public function changeStatiscs($uids,$qid){
		$cid = Session::$user["customerId"];
		log::write('LP2018131:'.$cid);
		log::write('LP2018131:'.$uids);
		log::write('LP2018131:'.$qid);
		Session::switchCustomer(0);
		$quanUserModel = M("quan_user");
		$miu_statistics = M("miu_statistics");
		$sale_statistics = M("salesource_statistics");
		$mimallModel = M("mimall_user");
		Session::switchCustomer($cid);
		$uids = explode(',',$uids);
		log::write('LP2018131:'.json_encode($uids));

		foreach($uids as $k=>$v){
			if(!empty($v)){
				$where['mi.miUid'] = $v;
				$where['mi.refereeUid'] = $v;
				$where['mi.preRefereeUid'] = $v;
				$where['_logic'] = "OR";
				$where_friend["_complex"] = $where;
				$where_friend["mi.qId"] = $qid;
				$where_friend["mi.uId"] = array('neq', $v);
				$where_friend["mi.cId"] = $cid;
				//统计密友好友数
				$miu_friendsCount = $mimallModel->alias("mi")
					->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
					->join("wx_".$cid."_user us on mi.uId = us.id")
					->join("wx_".$cid."_user_weixin_info wei on mi.uId = wei.userId")
					->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$cid)
					->where($where_friend)
					->count();
				log::write('LP2018131:'.$mimallModel->getLastSql());


				$whereMiu['mi.miUid'] = $v;
				$whereMiu['mi.refereeUid'] = $v;
				$whereMiu['mi.preRefereeUid'] = $v;
				$whereMiu['_logic'] = "OR";
				$where_miufriend["_complex"] = $whereMiu;
				$where_miufriend["mi.qId"] = $qid;
				$where_miufriend["mi.uId"] = array('neq', $v);
				$where_miufriend["mi.cId"] = $cid;
				$sql = "mi.uId = mi.miUid";
				$where_miufriend['_string'] = $sql;
				//统计密友注册好友数
				$miu_miuCount = $mimallModel->alias("mi")
					->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
					->join("wx_".$cid."_user us on mi.uId = us.id")
					->join("wx_".$cid."_user_weixin_info wei on mi.uId = wei.userId")
					->join("wx_miu_statistics st on mi.uId = st.uid and st.cid=".$cid)
					->where($where_miufriend)
					->count();
				$user = $miu_statistics->where(['uid' => $v, 'cid'=> $cid])->find();
				log::write('LP2018131:'.$mimallModel->getLastSql());

				if(empty($user)){
					$miuData['uid'] = $v;
					$miuData['cid'] = $cid;
					$miu_statistics->add($miuData);
				}
				$miu_statistics->where(['uid' => $v, 'cid' => $cid])->save(['friendCount' => $miu_friendsCount, 'miUCount' => $miu_miuCount]);

				log::write('LP2018131:'.$miu_statistics->getLastSql());


				$isSaleSource = $quanUserModel->where(['uid' => $v, 'qid' => $qid, 'deleted' => 0])->getField('isSaleSource');
				if($isSaleSource){
					$sale_friend['a.saleSource'] = $v;
					$sale_friend['a.cId'] = $cid;
					$sale_friend['a.qId'] = $qid;
					$sale_friend["a.uId"] = array('neq', $v);
					//统计销售源普通好友数
					$sale_friendsCount = $mimallModel->alias("a")
						->join("wx_quan_user b on a.qId=b.qid and a.uId=b.uid and b.deleted=0")
						->join("wx_".$cid."_user c on a.uId=c.id")
						->join("wx_".$cid."_user_weixin_info d on c.id=d.userId")
						->join("wx_miu_statistics st on a.uId = st.uid and st.cid=".$cid)
						->where($sale_friend)
						->count();
					log::write('LP2018131sale:'.$mimallModel->getLastSql());
					$sale_miufriend['a.saleSource'] = $v;
					$sale_miufriend['a.cId'] = $cid;
					$sale_miufriend['a.qId'] = $qid;
					$sale_miufriend["a.uId"] = array('neq', $v);
					$sql2 = "a.uId = a.miUid";
					$sale_miufriend['_string'] = $sql2;

					//统计销售源注册好友数
					$sale_miuCount = $mimallModel->alias("a")
						->join("wx_quan_user b on a.qId=b.qid and a.uId=b.uid and b.deleted=0")
						->join("wx_".$cid."_user c on a.uId=c.id")
						->join("wx_".$cid."_user_weixin_info d on c.id=d.userId")
						->join("wx_miu_statistics st on a.uId = st.uid and st.cid=".$cid)
						->where($sale_miufriend)
						->count();
					log::write('LP2018131sale:'.$mimallModel->getLastSql());
					$saleUser = $sale_statistics->where(['uid' => $v, 'cid'=> $cid])->find();
					if(empty($saleUser)){
						$saleData['uid'] = $v;
						$saleData['cid'] = $cid;
						$sale_statistics->add($saleData);
					}
					$sale_statistics->where(['uid' => $v, 'cid'=> $cid])->save(['friendCount' => $sale_friendsCount, 'miUCount' => $sale_miuCount]);
					log::write('LP2018131sale:'.$sale_statistics->getLastSql());
				}
			}
		}
	}

	public function getQuanUserById($id,$qid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer($cid);
		$MiUserModel = M("user");

		$condition["a.id"] = array("eq",$id);
		$condition["b.deleted"] = array("eq",0);
		$condition["b.qid"] = array("eq",$qid);
		$userInfo = $MiUserModel->alias("a")
			->join("wx_".$cid."_user_weixin_info wei on a.id = wei.userId")
			->join("wx_quan_user b on a.id=b.uid")
			->where($condition)
			->field("a.*,b.qid,b.isMiUDeliver,b.createTime,b.miCoins,b.totalRevenue as income,wei.headimgurl ")
			->find();
		$customInfo = $userInfo['customInfo'];
		$arrCustomerInfo = json_decode($customInfo, true);
        $userInfo['customInfo'] = $customInfo ? $arrCustomerInfo : [];
        $StatisData = $this->StatisData($cid,$qid,$id,1);
        $userInfo['profileUrl'] = $userInfo['headimgurl'];
        $userInfo['orderPrice'] = round($StatisData['buyOrderPrice'],2);
        $userInfo['orderCount'] = $StatisData['buyOrderCount'];
        $userInfo['friendCount'] = $StatisData['friendCount'];
        $userInfo['shareUv'] = $StatisData['shareUv'];
        $userInfo['miCoins'] = round($userInfo['miCoins'],2);
		$userInfo['income'] = round($userInfo['income'],2);
		if ($userInfo) {
			Output::instance()->object($userInfo);
		} else {
			Output::instance()->resultCode(code_success);
		}
	}



	public function addQuanUser($qid,$fullName = NULL,$phone = NULL){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}


		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("all_user");
		$quanModel = M("miyouquan");
		$quanUserModel = M("quan_user");
		$quanwhere['id']=$qid;
		$quanres=$quanModel->where($quanwhere)->find();
		$quanuserwhere['qid']=$qid;
		$quanuserwhere['deleted']=0;
		$quanuserwhere['status']=1;
		$quanUserCount=$quanUserModel->where($quanuserwhere)->count();
//		if($quanUserCount>=$quanres['miMaxCount']){
//		    Output::instance()->resultCode(1,'超出密友上线！');
//		    exit;
//		}


		$time=date("Y-m-d H:i:s");
		$rs=$MiModel->where("fullName='$fullName' and phone='$phone'")->find();
		if($rs && count($rs) > 0){
			$result=$rs['id'];
			//Output::instance()->resultCode(1,'密友已经存在！');
			//reutrn;
		}else{

			$time = date("Y-m-d H:i:s");
			$data["fullName"] = $fullName;
			$data["phone"] = $phone;
			$data["createTime"] = $time;
			$data["updateTime"] = $time;
			$result = $MiModel->add($data);

		}




		$MiQuanUserModel = M("quan_user");
		Session::switchCustomer($cid);
		$miquanwhere["qid"]=$qid;
		$miquanwhere["uid"]=$result;
		$miquanres=$MiQuanUserModel->where($miquanwhere)->find();
		if($miquanres){
			Output::instance()->resultCode(1,'圈内已存在该密友！');
			return;
		}else{
			$quaUserData["qid"]=$qid;
			$quaUserData["uid"]=$result;
			$quaUserData["name"]=$fullName;
			$quaUserData["identity"]=1;
			$quaUserData["createTime"]=$time;
			$quaUserData['status']=1;
			$quanUserResult = $MiQuanUserModel->add($quaUserData);
			//echo $MiQuanUserModel->getLastSql();
			if ($result) {
				$data["id"] = $result;
				Output::instance()->object($data);
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		}


	}





	public function updateQuanUser($id,$qid,$fullName = NULL,$phone = NULL,$wxId=null){

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$quanuser=M("quan_user");
		Session::switchCustomer($cid);
		$MiModel = M("user");


		$time = date("Y-m-d H:i:s");
		$data["fullName"] = $fullName;
		$data["phone"] = $phone;
		$data["wxNumber"]=$wxId;

		$result = $MiModel->where("id=$id")->save($data);
		$result1 = $quanuser->where("qid=$qid and uid=$id")->setField("wxId",$wxId);
		if ($result !== false&&$result1!==false) {
			$data["id"] = $id;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}




	public function deleteQuanUser($id,$uid,$type='del'){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("quan_user");
		$mimall = M("mimall_user");
		$quanModel = M("miyouquan");
		$quanteam = M("quan_team");
		$orderModel = M("module_product_order");
		$miu_statistics = M("miu_statistics");
		$saleSource_statistics = M("salesource_statistics");

		Session::switchCustomer($cid);
		$miuserInfo = $MiModel->where("qid=$id and uid=$uid and deleted=0")->find();
        $mimallInfo = $mimall->where("qId=$id and uId=$uid")->find();
        $time = date("Y-m-d H:i:s");
		if($type==0){
            if($miuserInfo['refereeUid']){
                $mimallData = $mimall->where(['uId'=> $miuserInfo['refereeUid'],'qId' => $id])->field('miUid,refereeUid,preRefereeUid,saleSource')->find();
                $mimall->where("qId=$id and uId=$uid")->save($mimallData);
			}else{
				$mimall->where("qId=$id and uId=$uid")->delete();
			}


			if($miuserInfo['teamId']){
				$nowTime = date("Y-m-1 0:0:0");
				$orderInfo = $orderModel->where("qId=$id and miUid = $uid and completionTime>'$nowTime' and status='ok'")
					->field("sum(price) as sales,count(id) as orders")->find();
				if(!$orderInfo['sales']){$orderInfo['sales']=0;}
				$sql = "UPDATE wx_quan_team SET totalPerson=totalPerson-1,totalSales=totalSales-".$orderInfo['sales'].",totalOrder=totalOrder-".$orderInfo['orders']." WHERE id=".$miuserInfo['teamId'];
				$quanteam->query($sql);
			}
			$data["deleted"] = 1;
			$data["updateTime"] = $time;
		}else{
			$quanwhere['id']=$id;
			$quanres=$quanModel->where($quanwhere)->find();
			$quanuserwhere['qid']=$id;
			$quanuserwhere['deleted']=0;
			$quanuserwhere['status']=1;
			$quanUserCount=$MiModel->where($quanuserwhere)->count();
//		    if($quanUserCount>=$quanres['miMaxCount']){
//		        Output::instance()->resultCode(1,'超出密友上线！');
//		        exit;
//		    }
			$mimallData['miUid']=$uid;
			$mimall->where("qId=$id and uId=$uid")->save($mimallData);
			$data["updateTime"] = $time;
			$data["deleted"] = 0;
			if($miuserInfo['teamId']){
				$nowTime = date("Y-m-1 0:0:0");
				$orderInfo = $orderModel->where("qId=$id and miUid = $uid and completionTime>'$nowTime' and status='ok'")
					->field("sum(price) as sales,count(id) as orders")->find();
				if(!$orderInfo['sales']){$orderInfo['sales']=0;}
				$sql = "UPDATE wx_quan_team SET totalPerson=totalPerson+1,totalSales=totalSales+".$orderInfo['sales'].",totalOrder=totalOrder+".$orderInfo['orders']." WHERE id=".$miuserInfo['teamId'];
				$quanteam->query($sql);
			}
		}
		$result = $MiModel->where("qid=$id and uid=$uid")->save($data);
		if ($result) {
            $this->deductRegisterPoint($uid, $id); //扣除积分
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

    /**退圈扣除积分
     * @param $userId
     * @param $qId
     */
	private function deductRegisterPoint($userId, $qId)
    {
        $customerId = Session::$user['customerId'];
        $inviteRewardModel = D('InviteReward', 'Logic');
        $pointModel = D('Point', 'Logic');

        $where = [
            'userId' => $userId,
            'type' => 2,
            'cid' => $customerId,
            'moduleId' => $qId,
            'deducted' => 0
        ];
        $inviteRecords = $inviteRewardModel->getInviteRecord($where);

        foreach ($inviteRecords as $inviteRecord) {
            $recordId = $inviteRecord['id'];
            $pointConfig = json_decode($inviteRecord['pointConfig'], true);

            /*扣除积分*/
            if (!empty($pointConfig['registerUserPoint']) && $pointConfig['userId']) { //扣除退出人积分
                $pointModel->deductPoint(
                    $pointConfig['userId'],
                    $pointConfig['registerUserPoint'],
                    'register',
                    $recordId,
                    '退出营销圈',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerPreMiPoint']) && $pointConfig['refereeUid']) { //扣除推荐人积分
                $pointModel->deductPoint(
                    $pointConfig['refereeUid'],
                    $pointConfig['registerPreMiPoint'],
                    'register',
                    $recordId,
                    '好友退出营销圈',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerPrePreMiPoint']) && $pointConfig['preRefereeUid']) { //扣除上级推荐人积分
                $pointModel->deductPoint(
                    $pointConfig['preRefereeUid'],
                    $pointConfig['registerPrePreMiPoint'],
                    'register',
                    $recordId,
                    '好友退出营销圈',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }

            if (!empty($pointConfig['registerRecommenderPoint']) && $pointConfig['recommenderId']) { //扣除推荐好友积分
                $pointModel->deductPoint(
                    $pointConfig['recommenderId'],
                    $pointConfig['registerRecommenderPoint'],
                    'register',
                    $recordId,
                    '好友退出营销圈',
                    '',
                    $pointConfig['pointSchemeId'],
                    $pointConfig['pointSchemeName']
                );
            }
            $where = ['id' => $inviteRecord['id']];
            $data = ['deducted' => 1];
            $res = $inviteRewardModel->updateInviteRecord($where, $data);
        }
    }
	//密友圈对应供应商接口  //LP 已修改
	public function getQuanVendorList($qid,$name=NULL,$order="quan.bingVendorTime", $orderBy="desc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
//		$QuanVendorModel = M("quan_vendor");
		$MiYouQuanModel = M("miyouquan");
		Session::switchCustomer($cid);

		$where["quan.id"] = array("eq",$qid);
		$where["ve.name"] = array("like","%".$name."%");
		$arr = $MiYouQuanModel
			->alias('quan')
			->where($where)
			->join("left join wx_mivendor as ve on quan.vid=ve.id")
			->order("$order $orderBy")
			->limit("$start, $limit")
			->field("*,quan.id as id")
			->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode(code_success);
		}


	}


	//密友圈未对应的应供应商接口  //LP 已修改
	public function getQuanVendorSelList($qid,$order="createTime", $orderBy="desc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$QuanVendorModel = M("mivendor");
		$MiYouQuanModel = M("miyouquan");
//		$QVendorModel = M("quan_vendor");
		Session::switchCustomer($cid);
		$arrwhere["id"]=$qid;
		$vid =$MiYouQuanModel->where($arrwhere)->getField('vid');

		$sel['vId']  = array('neq',$vid);
		$sel['deleted']  = 0;
		$sel['cId'] = array("eq",$cid);
		$arr = $QuanVendorModel
			->where($sel)
			->order("$order $orderBy")
			->limit("$start, $limit")
			->select();

		if ($arr) {
			$count = $QuanVendorModel->where($sel)->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}

	}

	public function getVendorSelList($qid,$order="a.createTime", $orderBy="desc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$QuanVendorModel = M("mivendor");
		$MiYouQuanModel = M("miyouquan");
//		$QVendorModel = M("quan_vendor");
		Session::switchCustomer($cid);
		$arrwhere["id"]=$qid;
		$vid =$MiYouQuanModel->where($arrwhere)->getField('vid');

		$sel['vId']  = array('neq',$vid);
		$sel['a.deleted']  = 0;
		$sel['b.customerId']  = $cid;
		$arr = $QuanVendorModel->alias("a")
			->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
			->field("a.*")
			->where($sel)
			->order("$order $orderBy")->limit("$start, $limit")->select();
		if ($arr) {
			$count = $QuanVendorModel->alias("a")
				->join("inner join wx_customer_user b on a.fromCustomerUserId=b.id")
				->where($sel)->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}

	}


	//密友圈添加供应商  LP已修改
	public function addQuanVendor($ids,$qid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
//		$MiModel = M("quan_vendor");
		$miYouQuanModel = M("miyouquan");
		$time = date("Y-m-d H:i:s");
		$result = $miYouQuanModel->where(['id' =>$qid])->save(['vid'=>$ids,'bingVendorTime' =>$time]);

		Session::switchCustomer($cid);
		if (is_numeric($result)) {
			$data["msg"] = "OK";
			$data["result"] = $vid;
			Output::instance()->object($data);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}



	//删除密友圈对应的供应商  LP已修改
	public function deleteQuanVendor($qid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
//		$MiModel = M("quan_vendor");
		$miYouQuanModel = M("miyouquan");
		Session::switchCustomer($cid);


		$data['vid'] = '';
		$data['bingVendorTime'] = '';
		$data['isSynchro'] = 0;
		$result = $miYouQuanModel->where("id=$qid")->save($data);
		if (is_numeric($result)) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}


	public function addMiRedenvelopeLog($arr){
		// 密友圈结束 deleteQuanVendor
		log::write('进入提现记录方法 addMiRedenvelopeLog');
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$Rlog = M("miredenvelope_log");
		Session::switchCustomer($customerId);
		$adddata["mch_billno"] = $arr['mch_billno'];
		$adddata["mch_id"] = $arr['mch_id'];
		$adddata["wxappid"] = $arr['wxappid'];
		$adddata["re_openid"] = $arr['re_openid'];
		$adddata["createTime"] = date("Y-m-d H:i:s");
		$adddata["result_code"] = $arr['result_code'];;
		$adddata["return_msg"] = $arr['return_msg'];;
		$adddata["total_amount"] = $arr['total_amount'];
		$adddata["send_name"] = $arr['send_name'];
		$adddata["wishing"] =$arr['wishing'];
		$resultPro = $Rlog->add($adddata);
		log::write('提现记录sql'.$Rlog->getLastSql());
		return $resultPro;
	}


	public function addTransferAccountsLog($arr){
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$Rlog = M("miconins_transferaccounts");
		Session::switchCustomer($customerId);
		$arr["createTime"] = date("Y-m-d H:i:s");
		$resultPro = $Rlog->add($arr);
		return $resultPro;
	}


	public function deleteQuanUserByTime($noBindDay=7,$noShareDay=30,$noMoneyDay=60){
		$cid = Session::$user["customerId"];
		$datatime=date('Y-m-d H:i:s');
		Session::switchCustomer(0);
		$quanuser = M("quan_user"); //用户表
		$mishare = M("mishare_from");//分享表
		$productorder = M("module_product_order");//订单表
		Session::switchCustomer($cid);

		// --删除7天未绑定的
		$noBindwhere['identity']=1;
		$noBindwhere["isAddWeinInfo"]=0;
		//$noBindwhere["createTime"]=array('elt',date('Y-m-d H:i:s',strtotime("$datatime -$noBindDay day")));
		$noBindArr=$quanuser->field('id')->where($noBindwhere)->select();
		log::write('七天未绑定查询：'.$quanuser->getLastSql());
		$resWhere["updateTime"]=array('elt',date('Y-m-d H:i:s',strtotime("$datatime -$noBindDay day")));
		$noBind=self::deleteQuanUserByArrayId($noBindArr,'删除七天未绑定的密友数:','in',$resWhere);
		// --删除7天未绑定的


		// --删除三十天未分享的
		//select distinct qu.id from wx_quan_user as qu left join wx_mishare_from as sf on qu.uid=sf.miUid and qu.qid=sf.quanId
		$noShareWhere["sf.createTime"]=array('egt',date('Y-m-d H:i:s',strtotime("$datatime -$noShareDay day")));
		$shareArr=$quanuser->alias('qu')->join("inner join wx_mishare_from as sf on qu.uid=sf.miUid and  qu.qid=sf.quanId")->field("qu.id")->distinct(true)->where($noShareWhere)->select();
		log::write('三十天有分享查询语句：'.$quanuser->getLastSql());
		$resWhere["updateTime"]=array('elt',date('Y-m-d H:i:s',strtotime("$datatime -$noShareDay day")));
		$noShare=self::deleteQuanUserByArrayId($shareArr,'删除三十天未分享的密友数:','not in',$resWhere);
		// --删除三十天未分享的

		// --删除六十天无收入的
		//select distinct qu.id from wx_quan_user as qu left join wx_module_product_order as po on qu.uid=po.miUid and qu.qid=po.qId
		// $noShareWhere["isAddWeinInfo"]=0;
		$noMoneyWhere["po.createTime"]=array('egt',date('Y-m-d H:i:s',strtotime("$datatime -$noMoneyDay day")));
		$moneyArr=$quanuser->alias('qu')->join("inner join wx_module_product_order as po on qu.uid=po.miUid and qu.qid=po.qId")->field("qu.id")->distinct(true)->where($noMoneyWhere)->select();
		log::write('六十天有收入查询语句：'.$quanuser->getLastSql());
		$resWhere["updateTime"]=array('elt',date('Y-m-d H:i:s',strtotime("$datatime -$noMoneyDay day")));
		$noMoney=self::deleteQuanUserByArrayId($moneyArr,'删除六十天无收入的密友数:','not in',$resWhere);
		// --删除六十天无收入的
	}
	protected  function deleteQuanUserByArrayId($arr,$des,$type='in',$resWhere){
		$timerLog = M("module_timer_log");	//定时器日志表
		$quanuser = M("quan_user"); //用户表
		/*   foreach ($arr as $key=>$val){
              $str.=$val['id'].',';

          }
          $str=substr($str, 0,strlen($str)-1);	 */
		$str=self::arrayToStringByArrId($arr);
		$resWhere['id']=array($type,"$str");
		$delRes['deleted']=1;
		$delRes['updateTime']=date('Y-m-d H:i:s');
		//无分享和收入删除绑定的密友
		if($type != 'in'){
			$resWhere['isAddWeinInfo']=1;
		}
		$resWhere['identity']=1;
		$res=$quanuser->where($resWhere)->save($delRes);
		log::write('删除密友语句：'.$quanuser->getLastSql());
		//所有的记录更新状态  0成功 1失败
		if(false == $res){
			$timerStatus=1;
			$str='';
		}else{
			if($type == 'in'){
				$resStr=$str;
				log::write('存储结果：'.$quanuser->getLastSql());
			}else{
				$resarr=$quanuser->field('id')->where($resWhere)->select();
				log::write('存储结果：'.$quanuser->getLastSql());
				/* foreach ($resarr as $key=>$val){
                   $str.=$val['id'].',';
                }
                $resStr=substr($str, 0,strlen($str)-1); */
				$resStr=self::arrayToStringByArrId($resarr);
			}
			$timerStatus=0;
			//更新成功
		}
		$timeData["createTime"]=date('Y-m-d H:i:s');
		$timeData["status"]=$timerStatus;
		$timeData["description"]=$des.$res;
		$timeData["moudle"]='quanuser';
		$timeData["oids"]=$resStr;
		$timeid=$timerLog->add($timeData);
	}

	public function arrayToStringByArrId($arr){
		foreach ($arr as $key=>$val){
			$str.=$val['id'].',';
		}
		return substr($str, 0,strlen($str)-1);
	}

	/**
	 * [rollbackAccount 神器红包退款]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function rollbackAccount($osid=null) {
		$platCustomerId=C("PLANT_CUSTOMERID");
		Session::switchCustomer(0);
		$MiUserShareModel = M("miuser_share");
		$MiQuanUserModel = M("quan_user");
		$miAccountModel = M("miaccount_friend");
		Session::switchCustomer($platCustomerId);
		$time=date("Y-m-d H:i:s");
		//查找要处理的数据
		if(!$osid) {
			$sql="select * from wx_miuser_share where status=0 and isRed=1 and overtotal>0 and NOW() > date_add(createTime, interval 24 hour) ";
		} else {
			$sql="select * from wx_miuser_share where id=$osid";
		}
		$shareList=$MiUserShareModel->query($sql);
		Log::write($MiUserShareModel->getlastsql());
		Log::write("进入退款状态".$id);
		foreach ($shareList as $key => $val) {
			$total=0;
			$id=$val["id"];
			$uid=$val["uId"];
			$qId=$val["qId"];
			$rollaccount=$val["overtotal"];//需要退款的金额
			$MiUserShareModel->startTrans();
			$upData["status"]=2;
			$upData["rolltotal"]=$rollaccount;
			if($rollaccount <= 0) {
				continue;
			}
			$success1=$MiUserShareModel->where("id=$id")->save($upData);
			Log::write($MiUserShareModel->getlastsql());
			//扣除账户余额添加红包记录
			$success2=$MiUserShareModel->query("update wx_quan_user set miCoins=miCoins+".$rollaccount." where uid=$uid and qid=$qId");
			//添加收入记录
			$addData1=array(
				"module"=>"shenqi",
				"moduleId"=>$id,
				"uId"=>$uid,
				"quanId"=>$qId,
				"vId"=>0,
				"description"=>$param->title."分享红包退款",
				"sId"=>0,
				"vsistId"=>0,
				"money"=>$rollaccount,
				"type"=>0,
				"createTime"=>date("Y-m-d H:i:s"),
				"deleted"=>0
			);
			$success3=$miAccountModel->add($addData1);
			Log::write($miAccountModel->getlastsql());
			if($success1!==false && $success2!==false && $success3!==false) {
				Log::write("成功");
				if($osid) {
					return true;
				}
				$MiUserShareModel->commit();
			} else {
				if($osid) {
					return false;
				}
				$MiUserShareModel->rollback();
			}
		}
	}
	/**
	 * [deleteunsubscribeUser 处理非关注密友]
	 * @return [type] [description]
	 */
	public function deleteunsubscribeUser(){
		$platCustomerId=C("PLANT_CUSTOMERID");
		Session::switchCustomer(0);
		$MiQuanUserModel = M("quan_user");
		Session::switchCustomer($platCustomerId);
		$userList=$MiQuanUserModel->query("select * from wx_".$platCustomerId."_user where `status`='unsubscribe'");
		Log::write($MiQuanUserModel->getlastsql());
		if($userList) {
			foreach ($userList as $key => $user) {
				$openid=$user["userName"];
				//查找weixinUserId
				$weixinInfo=$MiQuanUserModel->query("select id from wx_".$platCustomerId."_user_weixin_info where openid='$openid'");
				Log::write($MiQuanUserModel->getlastsql());
				if($weixinInfo && count($weixinInfo) > 0){
					$weixinUserId=$weixinInfo[0]["id"];
					//查找uId
					$userInfo=$MiQuanUserModel->query("select * from wx_all_user where weixinUserId=$weixinUserId");
					Log::write($MiQuanUserModel->getlastsql());
					if($userInfo && count($userInfo) > 0) {
						$uId=$userInfo[0]["id"];
						$MiQuanUserModel->query("update wx_quan_user set deleted=1 where uid=$uId");
						Log::write($MiQuanUserModel->getlastsql());
					}
				}
			}
		}
	}
	public function getUserId($userName) {
		$customerId = C("PLANT_CUSTOMERID");
		$WeixinUserModel=M($customerId."_user_weixin_info");
		$weixinResult=$WeixinUserModel->where("openid='".$userName."'")->find();
		$userModel=M("all_user");
		if($weixinResult){
			$weixinUserId=$weixinResult["id"];
		}
		$result=$userModel->where("weixinUserId='".$weixinUserId."'")
			->field("id")->find();
		if($result && count($result) > 0 ){
			$uid=$result["id"];
		}
		return $uid;
	}

	/**
	 * 密友圈 - 团队结算
	 * 服务器定时任务调用 - crontab -e (用root用户登录查看)
	 *
	 * Example of job definition:
	 * .---------------- minute (0 - 59)
	 * |  .------------- hour (0 - 23)
	 * |  |  .---------- day of month (1 - 31)
	 * |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
	 * |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
	 * |  |  |  |  |
	 * *  *  *  *  * user-name command to be executed
	 * 0  0  1  *  * /usr/bin/curl http://www.mboxone.com/wx/MiYouQuan/teamMonthStatistics.json >> test.log
	 * 每个月1号执行
	 */
	public function teamMonthStatistics(){

		/** 1. 实例化数据模型 */
		$customerId= Session::$user['customerId'];
		Session::switchCustomer(0);
		$quanTeam = M("quan_team");
		$quanuser = M("quan_user");
		$userMonth = M("quan_user_month_statistics");
		$sql = M("");
		$micconuntFriend = M("miaccount_friend");
		$teamMonth = M("quan_team_month_statistics");
		$tixianModel = M("miconis_tixian");
		Session::switchCustomer($customerId);

		$nowtime  = date('Y-m-1 0:0:0');    // 当前月时间 2017-07-01 00:00:00
		$prevTime = date('Y-m-1 0:0:0',strtotime("$nowtime -1 month")); // 之前一月时间 2017-06-01 00:00:00
		\Log::write('bug_teamMonthStatistics_$nowtime = ' . $nowtime);
		\Log::write('bug_teamMonthStatistics_$prevTime = ' . $prevTime);
		\Log::write('bug_teamMonthStatistics_date = ' . date('Y-m-d H:i:s'));

		$teamWhere["a.deleted"]=array("eq",0);
		$teamWhere["b.deleted"]=array("eq",0);
		$teamWhere["b.status"]=array("eq",1);
		$teamWhere["c.status"]=array("eq","ok");
		// 订单完成时间在上一个自然月内
		$teamWhere["_string"]="c.completionTime>'$prevTime' and c.completionTime<'$nowtime'";

		$teamList = $quanTeam->alias("a")
			->join("inner join wx_quan_user b on a.id=b.teamId")
			->join("inner join wx_module_product_order c on b.qid=c.qId and c.miUid=b.uid")
			->join("inner join wx_miyouquan d on b.qid=d.id")
			->where($teamWhere)
			->field("a.id,d.id as qid,a.createTime,count(c.id) as orderCount,a.totalPerson,sum(c.price) as sales,d.json,a.teamLeader")
			->group("a.id")
			->order("a.id")
			->select();
		\Log::write('bug_teamMonthStatistics_$quanTeam sql = ' . $quanTeam->getLastSql());
		\Log::write('bug_teamMonthStatistics_$teamList = ' . json_encode($teamList));

		$date = date("Y-m-d H:i:s");
		foreach($teamList as $teamIndex => $team) {
			/** 2017-11-01 团队奖励 奖励了两次, 错误原因不明, 可能是: 1. 定时任务执行了两次 */
			// 1. 无论是何原因, 只需要奖励一次, 那么去数据库 quan_team_month_statistics 里查询, 如果该月该团队已有了奖励, 则不在对该团队进行奖励
			$teamId = $teamMonth->where(['createTime' => ['EGT', $nowtime], 'teamId' => $team["id"]])->getField('teamId');
			\Log::write('bug_teamMonthStatistics_1 $teamMonth sql = ' . $teamMonth->getLastSql());
			\Log::write('bug_teamMonthStatistics_1 $teamId = ' . $teamId);
			if ($teamId) {  // 如果这个月, 这个团队已经奖励了, 则跳过
				continue;
			}

			// 新团队成员 - e.g. 2017-06-01 00:00:00 < 加入时间 < 2017-07-01 00:00:00
			$team['persons'] = $quanuser->where("teamId=".$team['id']." and joinTeamTime>'$prevTime' and joinTeamTime < '$nowtime' and status=1 and deleted=0")->count();
			// 老团队成员 - e.g. 加入时间 < 2017-06-01 00:00:00
			$team['oldTotalPerson'] =$quanuser->where("teamId=".$team['id']." and joinTeamTime<'$prevTime' and status=1 and deleted=0")->count();

			$teamData = NULL;
			$data=NULL;
			$teamData["totalPerson"]=$team['oldTotalPerson'];
			$teamData["teamId"]=$team["id"];
			$teamData["sales"]=$team["sales"];
			$teamData["person"]=$team["persons"];
			$teamData["order"]=$team["orderCount"];
			$teamData["createTime"]=date('Y-m-d H:i:s');
			$teamData["avgSales"]=$team["sales"]/$team["totalPerson"];

			// 判断团队创建时间
			if(strtotime($team['createTime'])>strtotime($prevTime)){
				$personRate=1;
			}else{
				// 新增成员比例
				$personRate = $team["persons"]/$team["oldTotalPerson"];
			}

			// 计算团长奖励
			$reward=0;
			if($team['json']){
				/**
				{
				"salcesReward": {
				"personNum": "3",
				"newPersonRatio": "1",
				"avgSales": "10",
				"reward": "1",
				"basicSales": "10",
				"addSales": "5",
				"addReward": "1",
				"maxReward": "3",
				"probation": ""
				},
				"joinCondition": {
				"singleShopping": {
				"status": 1,
				"condition": "0.01"
				},
				"totalShopping": {
				"status": 0,
				"condition": ""
				}
				}
				}
				 */
				$rewardJson = json_decode($team['json'],true);
				if($rewardJson['salcesReward']){
					$salce = $rewardJson['salcesReward'];

					// 团长奖励条件
					if($team['totalPerson']>=$salce['personNum']        // 团队满多少人
						&&$personRate*100>=$salce['newPersonRatio']     // 并且新增**%合伙人
						&&$teamData["avgSales"]>=$salce['avgSales']     // 平均销售额达到***
					) {
						if($teamData['avgSales']>($salce['basicSales']+$salce['addSales'])){
							$grade = intval(($teamData['avgSales']-$salce['basicSales'])/$salce['addSales']);
							$reward = $grade*$salce['addReward']+$salce['reward'];
							if($reward>$salce['maxReward']){
								$reward = $salce['maxReward']/100;
							}else{
								$reward = $reward/100;
							}

						}else{
							$reward = $salce['reward']/100;
						}
					}
				}
			}
			$salceReward = $reward*$team['sales'];
			$teamData["salesReward"]=$salceReward;
			$teamMonthId = $teamMonth->add($teamData);
			\Log::write('bug_teamMonthStatistics_$teamMonth add_sql = ' . $teamMonth->getLastSql());
			\Log::write('bug_teamMonthStatistics_$teamMonthId = ' . json_encode($teamMonthId));

			// 2. 无论是何原因, 只需要奖励一次, 那么去数据库 quan_team_month_statistics 里查询, 如果该月该团队已有了奖励, 则不在对该团队进行奖励
			$teamIds = $teamMonth->where(['createTime' => ['EGT', $nowtime], 'teamId' => $team["id"]])->getField('teamId', TRUE);
			\Log::write('bug_teamMonthStatistics_2 $teamMonth sql = ' . $teamMonth->getLastSql());
			\Log::write('bug_teamMonthStatistics_2 $teamIds = ' . json_encode($teamIds));
			if (count($teamIds) >= 1) {  // 大于等于1, 表示已经出错了, 但是不能给团队团长加钱了, 退出
				continue;
			}

			if($salceReward) {
				$data = null;
				$data["module"] = "teamSalces";
				$data["quanId"] = $team["qid"];
				$data["moduleId"] = $teamMonthId;
				$data["uId"] = $team["teamLeader"];
				$data["description"] = date("Y") . '年' . date("m") . "月团队销售额奖励";
				$data["money"] = $salceReward;
				$data["type"] = 0;
				$data["createTime"] = $date;
				$data["deleted"] = 0;

				// 3. 无论是何原因, 只需要奖励一次, 如果这个月已经发过来, 就会存在这个通知信息, 则不给用户加钱, 跳出
				$Where_MiaccountFriend = [
					'module' => "teamSalces",
					'quanId' => $team["qid"],
					'uId' => $team["teamLeader"],
					'description' => date("Y") . '年' . date("m") . "月团队销售额奖励",
					'money' => $salceReward
				];
				$Res_MiaccountFriend = $micconuntFriend->where($Where_MiaccountFriend)->select();
				\Log::write('bug_teamMonthStatistics_3 $teamMonth sql = ' . $teamMonth->getLastSql());
				\Log::write('bug_teamMonthStatistics_3 $teamIds = ' . json_encode($teamIds));
				if ($Res_MiaccountFriend) {
					continue;
				}

				$micconuntFriend->add($data);
				\Log::write('bug_teamMonthStatistics_$micconuntFriend = ' . $micconuntFriend->getLastSql());
				$query = "UPDATE wx_quan_user
                          SET miCoins = miCoins + $salceReward,totalRevenue=totalRevenue+$salceReward
                          WHERE qid = " . $team["qid"] . " AND uid  = " . $team["teamLeader"];
				$sql->query($query);
				\Log::write('bug_teamMonthStatistics_$sql = ' . $sql->getLastSql());
			}
		}

		// 4. 无论是何原因, 只需要奖励一次, 遍历这些团队, 如果有团队奖励了两次, 则把钱扣回来 => 在下面接口里

		//合伙人月统计
		$quanuserWhere["b.deleted"]=array("eq",0);
		$quanuserWhere["b.status"]=array("eq",1);
		$quanUserList = $quanuser->alias("b")
			->join("left join wx_module_product_order c on b.qid=c.qId and c.miUid=b.uid and c.status='ok' and c.completionTime>'$prevTime' and c.completionTime<'$nowtime'")
			->where($quanuserWhere)
			->field("b.qid,b.uid,count(c.id) as orderCount,sum(c.price) as sales")
			->group("b.id")
			->select();
		foreach($quanUserList as $userIndex=>$userStatistics){
			!$userStatistics['sales']?$userStatistics['sales']=0:"";
			$revenueInfo = $micconuntFriend->where("quanId=".$userStatistics['qid']." and uId=".$userStatistics['uid']." and type=0 and createTime>'$prevTime' and createTime<'$nowtime'")->field("sum(money) as revenue")->find();
			$tixianInfo = $tixianModel->where("quanId=".$userStatistics['qid']." and uId=".$userStatistics['uid']." and state=1 and createTime>'$prevTime' and createTime < '$nowtime'")->field("sum(cash) as tixian")->find();
			$userData[$userIndex]["quanId"]=$userStatistics['qid'];
			$userData[$userIndex]["uId"]=$userStatistics['uid'];
			$userData[$userIndex]["sales"]=$userStatistics['sales'];
			$userData[$userIndex]["order"]=$userStatistics['orderCount'];
			$userData[$userIndex]["revenue"]=$revenueInfo['revenue'];
			$userData[$userIndex]["tixian"]=$tixianInfo['tixian'];
			$userData[$userIndex]["createTime"]=$nowtime;
		}
		$userMonth->addAll($userData);

	}

	/**
	 * 每个月修改团队奖励金额多发的问题
	 */
	public function fixTeamMonthStatistics()
	{
		/** 1. 实例化数据模型 */
		$customerId= Session::$user['customerId'];
		Session::switchCustomer(0);
		$quanTeam = M("quan_team");
		$quanuser = M("quan_user");
		$userMonth = M("quan_user_month_statistics");
		$sql = M("");
		$micconuntFriend = M("miaccount_friend");
		$teamMonth = M("quan_team_month_statistics");
		$tixianModel = M("miconis_tixian");
		Session::switchCustomer($customerId);

		$nowtime  = date('Y-m-1 0:0:0');    // 当前月时间 2017-07-01 00:00:00
		$prevTime = date('Y-m-1 0:0:0',strtotime("$nowtime -1 month")); // 之前一月时间 2017-06-01 00:00:00

		$teamWhere["a.deleted"]=array("eq",0);
		$teamWhere["b.deleted"]=array("eq",0);
		$teamWhere["b.status"]=array("eq",1);
		$teamWhere["c.status"]=array("eq","ok");
		// 订单完成时间在上一个自然月内
		$teamWhere["_string"]="c.completionTime>'$prevTime' and c.completionTime<'$nowtime'";

		$teamList = $quanTeam->alias("a")
			->join("inner join wx_quan_user b on a.id=b.teamId")
			->join("inner join wx_module_product_order c on b.qid=c.qId and c.miUid=b.uid")
			->join("inner join wx_miyouquan d on b.qid=d.id")
			->where($teamWhere)
			->field("a.id,d.id as qid,a.createTime,count(c.id) as orderCount,a.totalPerson,sum(c.price) as sales,d.json,a.teamLeader")
			->group("a.id")
			->order("a.id")
			->select();
		\Log::write('bug_fix_teamMonthStatistics_$quanTeam sql = ' . $quanTeam->getLastSql());
		\Log::write('bug_fix_teamMonthStatistics_$teamList = ' . json_encode($teamList));

		// 4. 循环遍历, 如果发多了, 就把钱扣回来
		foreach($teamList as $teamIndex => $team) {
			// 2. 无论是何原因, 只需要奖励一次, 那么去数据库 quan_team_month_statistics 里查询, 如果该月该团队已有了奖励, 则不在对该团队进行奖励
			$salesRewards = $teamMonth->where(['createTime' => ['EGT', $nowtime], 'teamId' => $team["id"]])->getField('salesReward', TRUE);
			if (count($salesRewards) > 1) {  // 大于等于1, 表示已经出错了, 需要把钱扣回来

				for ($i = 1; $i < count($salesRewards); $i++) {
					$salceReward = $salesRewards[$i];

					$query = "UPDATE wx_quan_user
                          SET miCoins = miCoins - $salceReward, totalRevenue = totalRevenue - $salceReward
                          WHERE qid = " . $team["qid"] . " AND uid  = " . $team["teamLeader"];
					$sql->query($query);
					\Log::write('bug_fix_teamMonthStatistics_$sql = ' . $sql->getLastSql());
				}
			}
		}
	}

	/**
	 * 密友时间树
	 * @param $uid			用户id
	 * @param int $start	开始条数
	 * @param int $limit	每页多少条
	 */
	public function userActionList($uid,$cid, $start = 0, $limit = 10){
		Session::switchCustomer(0);
		$user_action = M('user_action');
		$where['uid'] = $uid;
		$where['cid'] = $cid;
		$arr = $user_action->where($where)->order('actionTime desc')->limit($start,$limit)->select();
		$count = $user_action->where($where)->count();
//		$count = $user_action->where("uid=$uid")->group('day(actionTime)')->order('actionTime desc')->field('actionTime')->select();
//		$count = count($count);
		foreach($arr as $key => $value){
			$arr[$key]['content'] = $this->event($value['event'],$value['params']);
		}
		$Out = [
			'code'  => 0,
			'msg'  => '获取成功',
			'data'  => $arr,
			'count'  => $count
		];
		Output::instance()->object($Out);
	}

	/**
	 * 事件处理
	 * @param $event		事件
	 * @param $params		json
	 * @return string
	 */
	public function event($event,$params)
	{
		$params = json_decode($params,true);
		$params['shareType'] == 1 ? $shareType = '好友' : $shareType = '朋友圈';
		switch ($event) {
			case buy:
				if($params['type'] == 'form'){
					return '提交信息：' . $params['name'];
				}else{
					return '购买商品：' . $params['name'];
				}

				break;
			case productShare:
				return '分享商品：' . $params['name'] . '<br/>分享对象:' . str_repeat(' ',10) . $shareType;
				break;
			case mallShare:
				return '分享商城：' . $params['name'] . '<br/>分享对象:' . str_repeat(' ',10) . $shareType;
				break;
			case miContentShare:
				return '分享内容：' . $params['title'] . '<br/>分享对象:' . str_repeat(' ',10) . $shareType;
				break;
			case productView :
				return '浏览商品：' . $params['name'];
				break;
			case mallView:
				return '浏览商城：' . $params['name'];
				break;
			case miContentView :
				return '浏览内容：' . $params['title'];
				break;
			case recommendMiU :
				return '推荐好友：' . $params['nickName'];
				break;
		}
	}
	/**
	 * 员工可自动加入圈列表
	 */
	public function getEmployeeQuanList(){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MiModel = M("miyouquan");
		Session::switchCustomer($cid);
		$where['cId'] = array("eq",$cid);
		$where['staffJoin'] = array("eq",1);
		$arr = $MiModel->where($where)->field('id, name')->order("createTime desc")->select();
		//Log::write('jie---11'.$MiModel->getLastSql());
		if ($arr) {
			Output::instance()->object([
				'code'=>0,
				'results'=>$arr
			]);
		} else {
			Output::instance()->object([
				'code'=>1,
				'results'=>[]
			]);
		}
	}

	/**
	 * 审核用户功能
	 * @param $id  id
	 * @param $qid  圈id
	 * @param $status   审核结果，默认为1
	 */
	public function auditQuanUser($id,$qid,$status,$price = 0,$salePrice = ''){
		//参数组合
		$params = new stdClass();
		$params->id = $id;
		$params->qid = $qid;
		$params->status = $status;
		$params->price = $price;
		$params->salePrice = $salePrice;
		//调用module
		Module::callModule("quan", NULL, "auditQuanUser", $params);

	}

	/**
	 * 更换所有者
	 * @param $oldLordId  原主公uid
	 * @param $newLordId  新主公uid
	 * @param $qid   圈id
	 */
	public function chengeLord($oldLordId='',$newLordId,$qid){
		//是否原有主公，没有的话直接就升级为主公
		if (empty($oldLordId)){
			$data = $this->changeUserIden($qid,$qid,$newLordId,1);
			Output::instance()->object($data);
		}else{
			//有主公的话就先降为密友，再升为主公
			//将原主公降为密友
			$data = $this->changeUserIden($qid,$qid,$oldLordId,1);
			if ($data['code'] !== 0){
				Output::instance()->object($data);
			}else{
				//将密友升成主公
				$data = $this->changeUserIden($qid,$qid,$newLordId,1);
				Output::instance()->object($data);
			}
		}
	}

	// pc端好友列表，先暂时搁置。等逻辑清晰再做

	/**
	 * 添加内容时选择密友圈列表
	 */
	public function getSelectQuanList(){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$quan_tab = M('miyouquan');
		Session::switchCustomer($cid);
		//人数小于上限
		$quanList = $quan_tab->alias('q')
			->join('inner join wx_quan_user u q.id=u.qid')
			->where(['q.cId'=>$cid,])
			->field('q.id, q.name,q.miMaxCount,count(u.id) as miCount')
			->select();
		if($quanList == null){
			Output::instance()->object([
				'code'=>1,
				'msg'=>'暂无圈子',
				'results'=>[],
			]);
			return;
		}
		$result = [];
		foreach($quanList as $k=>$v){
			if($v['miCount']>=$v['miMaxCount']){
				continue;
			}
			$result[$k] = $v;
		}
		Output::instance()->object([
			'code'=>0,
			'msg'=>'OK',
			'results'=>$result
		]);
	}

	/**
	 * 	用户更换推荐人涉及到的数据调整
	 * @param $uid  用户uid
	 * @param $qid  qid,圈id
	 * @param $id  需要替换成的推荐人quid
	 */
	public function changeReferee($uid,$qid,$id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$quanUser = M("quan_user");
		$mimallUser = M("mimall_user");
		Session::switchCustomer($cid);

		/**2.数据查询*/
		$originalUserId = $uid;
		$replaceRefreeId = $quanUser->where("id=$id")->getField('uid');

		$where_quan_original['uid'] = $originalUserId;
		$where_quan_original['qid'] = $qid;
		$where_quan_original['deleted'] = 0;
		$isSaleSource = $quanUser->where($where_quan_original)->getField('isSaleSource');
		if ($isSaleSource){
			$return['code'] = 1;
			$return['msg'] = '销售源不可更换推荐人';
			$return['data'] = [];
			Output::instance()->object($return);
			return;
		}
		//查询原有用户信息
		$where_original['qId'] = $qid;
		$where_original['uId'] = $originalUserId;
		$where_original['cId'] = $cid;
		$originalUserInfo = $mimallUser->field('saleSource,refereeUid,preRefereeUid')->where($where_original)->find();
		//查询推荐人信息
		$where_replace['qId'] = $qid;
		$where_replace['uId'] = $replaceRefreeId;
		$where_replace['cId'] = $cid;
		$replaceUserInfo = $mimallUser->field('saleSource,refereeUid,preRefereeUid')->where($where_replace)->find();
		/**3.数据替换*/
		$quanUser->startTrans();
		$time = date("Y-m-d H:i:s");
		//开始替换miUId为原有uid的用户信息
		$where_miUid_replace['qId'] = $qid;
		$where_miUid_replace['miUid'] = $originalUserId;
		$data_miUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_miUid['refereeUid'] = $replaceRefreeId;
		$data_miUid['preRefereeUid'] = $replaceUserInfo['refereeUid'];
		$data_miUid['updateTime'] = $time;
		$miUid_result = $mimallUser->where($where_miUid_replace)->save($data_miUid);

		//开始替换refereeUid为原有uid的用户信息
		$where_refereeUid_replace['qId'] = $qid;
		$where_refereeUid_replace['refereeUid'] = $originalUserId;
		$data_refereeUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_refereeUid['preRefereeUid'] = $replaceRefreeId;
		$data_refereeUid['updateTime'] = $time;
		$refereeUid_result = $mimallUser->where($where_refereeUid_replace)->save($data_refereeUid);

		//开始替换preRefereeUid为原有uid的用户信息
		$where_preRefereeUid_replace['qId'] = $qid;
		$where_preRefereeUid_replace['preRefereeUid'] = $originalUserId;
		$data_preRefereeUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_preRefereeUid['updateTime'] = $time;
		$preRefereeUid_result = $mimallUser->where($where_preRefereeUid_replace)->save($data_preRefereeUid);

		$condition["qid"]=array("eq",$qid);
		$condition["uid"]=array("eq",$uid);
		$condition["deleted"]= 0;
		$data["refereeUid"] = $replaceRefreeId;
		$data["saleSource"] = $replaceUserInfo['saleSource'];
		$data["updateTime"] = date("Y-m-d H:i:s");
		$save_result = $quanUser->where($condition)->save($data);
		$uids = $originalUserInfo['saleSource'].','.$originalUserInfo['refereeUid'].','.$originalUserInfo['preRefereeUid'].','.$replaceUserInfo['saleSource'].','.$replaceUserInfo['refereeUid'].','.$replaceUserInfo['preRefereeUid'].','.$replaceRefreeId;
		$this->changeStatiscs($uids,$qid);
		if(( is_numeric($save_result)) &&  is_numeric($miUid_result) &&  is_numeric($refereeUid_result) &&  is_numeric($preRefereeUid_result)){
			$quanUser->commit();
			Output::instance()->resultCode();
		}else{
			$quanUser->rollback();
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 	用户身份替换涉及到的数据调整
	 * @param $uid  uid
	 * @param $qid  qid,圈id
	 * @param $changeUid  需要替换成的uid
	 */
	public function exchangeIdentity($qid,$uid,$changeUid){
        set_time_limit(0);
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$quanUser = M("quan_user");
		$mimallUser = M("mimall_user");
		Session::switchCustomer($customerId);
		/**2.数据查询*/
		$originalUserId = $uid;
		$replaceUserId = $changeUid;

		$where_quan_original['qid'] = $qid;
		$where_quan_original['uid'] = $originalUserId;
		$where_quan_original['deleted'] = 0;
		$originalUser = $quanUser->field('id,isSaleSource')->where($where_quan_original)->find();
		$where_quan_replace['qid'] = $qid;
		$where_quan_replace['uid'] = $replaceUserId;
		$where_quan_replace['deleted'] = 0;
		$replaceUser = $quanUser->field('id,isSaleSource')->where($where_quan_replace)->find();
		if ($originalUser['isSaleSource'] !== $replaceUser['isSaleSource']){
			$return['code'] = 1;
			$return['msg'] = '身份不同不可进行身份替换';
			$return['data'] = [];
			Output::instance()->object($return);
			return;
		}
		//查询原有用户信息
		$where_original['qId'] = $qid;
		$where_original['uId'] = $originalUserId;
		$where_original['cId'] = $customerId;
		$originalUserInfo = $mimallUser->field('saleSource,refereeUid,preRefereeUid,id')->where($where_original)->find();
		//查询替换者信息
		$where_replace['qId'] = $qid;
		$where_replace['uId'] = $replaceUserId;
		$where_replace['cId'] = $customerId;
		$replaceUserInfo = $mimallUser->field('saleSource,refereeUid,preRefereeUid')->where($where_replace)->find();
		/**3.数据替换*/
		$quanUser->startTrans();
		$time = date("Y-m-d H:i:s");
		//替换quan_user表中的数据refereeUid为原用户的。
		$where_quan_replace_refereeUid['qid'] = $qid;
		$where_quan_replace_refereeUid['deleted'] = 0;
		$where_quan_replace_refereeUid['refereeUid'] = $originalUserId;
		$data_quan_refereeUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_quan_refereeUid['refereeUid'] = $replaceUserId;
		$data_quan_refereeUid['updateTime'] = $time;
		$quan_refereeUid_result = $quanUser->where($where_quan_replace_refereeUid)->save($data_quan_refereeUid);
		//替换quan_user表中的数据saleSource为原用户的。
		$where_quan_replace_saleSource['qid'] = $qid;
		$where_quan_replace_saleSource['deleted'] = 0;
		$where_quan_replace_saleSource['saleSource'] = $originalUserId;
		$data_quan_saleSource['saleSource'] = $replaceUserId;
		$data_quan_saleSource['updateTime'] = $time;
		$quan_saleSource_result = $quanUser->where($where_quan_replace_saleSource)->save($data_quan_saleSource);
		//开始替换miUId为原有uid的用户信息
		$where_miUid_replace['qId'] = $qid;
		$where_miUid_replace['miUid'] = $originalUserId;
		$where_miUid_replace['cId'] = $customerId;
		$data_miUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_miUid['miUid'] = $replaceUserId;
		$data_miUid['refereeUid'] = $replaceUserInfo['refereeUid'];
		$data_miUid['preRefereeUid'] = $replaceUserInfo['preRefereeUid'];
		$data_miUid['updateTime'] = $time;
		$miUid_result = $mimallUser->where($where_miUid_replace)->save($data_miUid);
		//开始替换miUId为原有uid的用户信息
		$where_refereeUid_replace['qId'] = $qid;
		$where_refereeUid_replace['refereeUid'] = $originalUserId;
		$where_refereeUid_replace['cId'] = $customerId;
		$data_refereeUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_refereeUid['refereeUid'] = $replaceUserId;
		$data_refereeUid['preRefereeUid'] = $replaceUserInfo['refereeUid'];
		$data_refereeUid['updateTime'] = $time;
		$refereeUid_result = $mimallUser->where($where_refereeUid_replace)->save($data_refereeUid);
		//开始替换preRefereeUid为原有uid的用户信息
		$where_preRefereeUid_replace['qId'] = $qid;
		$where_preRefereeUid_replace['preRefereeUid'] = $originalUserId;
		$where_preRefereeUid_replace['cId'] = $customerId;
		$data_preRefereeUid['saleSource'] = $replaceUserInfo['saleSource'];
		$data_preRefereeUid['preRefereeUid'] = $replaceUserId;
		$data_preRefereeUid['updateTime'] = $time;
		$preRefereeUid_result = $mimallUser->where($where_preRefereeUid_replace)->save($data_preRefereeUid);
		//开始替换saleSource为原有uid的用户信息
		$where_saleSource_replace['qId'] = $qid;
		$where_saleSource_replace['saleSource'] = $originalUserId;
		$where_saleSource_replace['cId'] = $customerId;
		$data_saleSource['saleSource'] = $replaceUserInfo['saleSource'];
		$data_saleSource['updateTime'] = $time;
		$saleSource_result = $mimallUser->where($where_saleSource_replace)->save($data_saleSource);
		//删除mimall_user表中的数据，以及假删除quan_user表中数据
		$delete_result = $mimallUser->where("id=".$originalUserInfo['id'])->delete();
		$data_save_quan['deleted'] = 1;
		$data_save_quan['updateTime'] = $time;
		$save_result = $quanUser->where("id=".$originalUser['id'])->save($data_save_quan);
		//将这些替换完之后进行刘鹏的接口调用，进行统计数据的修改
		$uids = $originalUserInfo['saleSource'].','.$originalUserInfo['refereeUid'].','.$originalUserInfo['preRefereeUid'].','.$replaceUserInfo['saleSource'].','.$replaceUserInfo['refereeUid'].','.$replaceUserInfo['preRefereeUid'].','.$replaceUserId;
		$this->changeStatiscs($uids,$qid);
		if( is_numeric($quan_refereeUid_result) && is_numeric($quan_saleSource_result) && is_numeric($save_result) &&  is_numeric($miUid_result) &&  is_numeric($refereeUid_result) &&  is_numeric($saleSource_result) &&  is_numeric($delete_result)){
			$quanUser->commit();
			Output::instance()->resultCode();
			return;
		}else{
			$quanUser->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}

	}

	/**
	 * 开启密友配送功能
	 * @param $id				用户id
	 * @param $qid				营销圈id
	 * @param $isMiUDeliver	是否开启配送 1-开启/0-关闭
	 */
	public function isMiUDeliver($id,$qid,$isMiUDeliver){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$quan_user = M('quan_user');
		Session::switchCustomer($cid);
		$where['qid'] = array('eq', $qid);
		$where['uid'] = array('eq', $id);
		$where['deleted'] = array('eq', 0);
		$result = $quan_user->where($where)->setField('isMiUDeliver',$isMiUDeliver);
		if(is_numeric($result)){
			Output::instance()->object([
				'code'=>0,
				'msg'=>'修改成功',
			]);
		}else{
			Output::instance()->object([
				'code'=>1,
				'msg'=>'修改失败',
			]);
		}
	}

	public function rankList($qid){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MiQuanRankModel = M('miyouquan_setting_rank');
		Session::switchCustomer($cid);

		$rankInfo = $MiQuanRankModel->where(['qid' => $qid])->select();

		if($rankInfo){
			Output::instance()->object([
				'code'=>0,
				'msg'=>'获取成功',
				'data'=>$rankInfo,
			]);
		}else{
			Output::instance()->object([
				'code'=>1,
				'msg'=>'获取失败',
				'data'=>[],
			]);
		}
	}
	public function updateUserRank($qid,$userId,$userName,$rankId)
	{
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$QuanUserModel = M('quan_user');
		$MiQuanRankModel = M('miyouquan_setting_rank');
		Session::switchCustomer($cid);
		$where['uid'] = array('eq', $userId);
		$where['qid'] = array('eq', $qid);
		$where['deleted'] = array('eq', 0);
		$result = $QuanUserModel->where($where)->setField('rankId',$rankId);

		$fullName = Session::$user['fullName'];
		$rankName = $MiQuanRankModel->where(['id' => $rankId])->getField('rankName');
		R('Log/add',array('marketing','233','营销圈',op_update,$QuanUserModel->getLastSql(),$fullName.'修改'.$userName.'的级别为'.$rankName));


		if(is_numeric($result)){
			Output::instance()->object([
				'code'=>0,
				'msg'=>'修改成功',
			]);
		}else{
			Output::instance()->object([
				'code'=>1,
				'msg'=>'修改失败',
			]);
		}
	}

	/**
	 * 新增或者更新一个自定义菜单
	 * @param null $id
	 * @param $descript	/菜单名称
	 * @param $url	/菜单链接
	 * @param $menuIconUrl	/菜单图标
	 * @param $toolbarIconUrl	/工具栏图标
	 */
	public function saveMenuToolbar($id = null,$descript, $url, $menuIconUrl, $toolbarIconUrl)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$menuToolbar_table = M('quan_menu_toolbar');
		$miyouquan_table = M('miyouquan');
		Session::switchCustomer($cid);

		if(empty($descript) || empty($url) || empty($menuIconUrl) || empty($toolbarIconUrl)){
			Output::instance()->object([
				'code' => -1,
				'msg' => '各项不能为空',
				'results' => []
			]);
			return;
		}
		$data = [];
		$data['cid'] = $cid;
		$data['descript'] = $descript;
		$data['url'] = $url;
		$data['menuIconUrl'] = $menuIconUrl;
		$data['toolbarIconUrl'] = $toolbarIconUrl;
		$data['type'] = 0;
		$ret = false;
		$retId = 0;
		if($id){
			$data['updateTime'] = date('Y-m-d H:i:s');
			$retType = $menuToolbar_table->where('id ='.$id)->getField('type');
			if($retType){
				Output::instance()->object([
					'code' => -1,
					'msg' => '系统菜单无法编辑',
					'results' => []
				]);
				return;
			}
			M()->startTrans();
			$ret = $menuToolbar_table->where('id ='.$id)->save($data);
			if(!is_numeric($ret)){
				Log::write('更新自定义菜单失败:'.$menuToolbar_table->getLastSql());
				M()->rollback();
				Output::instance()->object([
					'code' => -1,
					'msg' => '更新失败',
					'results' => []
				]);
				return;
			}
			//更新所有使用了此菜单的圈子配置
			$quanCnfList = $miyouquan_table->where(['cId' =>$cid])->field('id, config')->select();
			foreach($quanCnfList as $key => $val){
				$val['config'] = json_decode($val['config'], true);

				$bool = false;
				//var_dump($val['config']['reveal']);exit;
				foreach($val['config']['reveal']['menu'] as $k=> $v){
					if(in_array($id, $v) && ($v['type'] == 0)){	//存在正在使用
						$v['descript'] = $descript;
						$v['url'] = $url;
						$v['menuIconUrl'] = $menuIconUrl;
						$val['config']['reveal']['menu'][$k] = $v;
						//$val['config']['reveal']['menu'] = json_encode($val['config']['reveal']['menu']);
						$bool = true;
					}
				}
				foreach($val['config']['reveal']['features'] as $featK=> $featV){
					if(in_array($id, $featV)  && ($featV['type'] == 0)){	//存在正在使用
						$featV['descript'] = $descript;
						$featV['url'] = $url;
						$featV['toolbarIconUrl'] = $toolbarIconUrl;
						$val['config']['reveal']['features'][$featK] = $featV;
						$bool = true;
					}
				}
				if($bool){
					$config = json_encode($val['config']);
					$updateRet = $miyouquan_table->where(['id' => $val['id']])->save(['config' => $config]);
					if(!is_numeric($updateRet)){
						M()->rollback();
						Output::instance()->object([
							'code' => -1,
							'msg' => '删除失败',
							'results' => []
						]);
					}
				}
			}
			M()->commit();
		}else{
			$data['createTime'] = date('Y-m-d H:i:s');
			$retId = $menuToolbar_table->add($data);
		}
		if(!is_numeric($ret) && !$retId){
			Log::write('保存自定义菜单失败:'.$menuToolbar_table->getLastSql());
			Output::instance()->object([
				'code' => -1,
				'msg' => '新增失败',
				'results' => []
			]);
			return;
		}
		Output::instance()->object([
			'code' => 0,
			'msg' => 'ok',
			'results' => []
		]);
	}

	/**
	 * 获取单个自定义菜单详情
	 * @param $id /自定义菜单id
	 */
	public function getMenuToolbarById($id)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$menuToolbar_table = M('quan_menu_toolbar');
		Session::switchCustomer($cid);
		$ret = $menuToolbar_table->where('id ='.$id .' and deleted = 0')->find();
		if($ret['type']){
			$massage = '系统菜单无法设置';
		}else if(!$ret){
			$massage = '暂无数据';
		}
		if(!$ret || $ret['type']){
			Log::write('查询自定义菜单失败:'.$menuToolbar_table->getLastSql());
			Output::instance()->object([
				'code' => -1,
				'msg' => $massage,
				'results' => []
			]);
			return;
		}
		Output::instance()->object([
			'code' => 0,
			'msg' => 'ok',
			'results' => $ret
		]);
	}

	/**
	 * 获取自定义菜单列表
	 * @param int $start	/分页起始
	 * @param int $limit	/分页大小
	 * @param string $order	/排序
	 * @param string $by	/排序
	 * @param int $type	/0:全部,1:返回自定义
	 */
	public function getMenuToolbarList($start = 0, $limit = 10, $order = 'createTime', $by = 'desc', $type=0)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$menuToolbar_table = M('quan_menu_toolbar');
		Session::switchCustomer($cid);
		$where = [];
		$where['cid'] = $cid;
		$where['deleted'] = 0;


		$where['cid'] = $cid;
		$where['deleted'] = 0;
		$where['type'] = 0;
		$map = [];
		if(!$type){
			$map['_complex'] = $where;
			$map['type'] =  ['NEQ', 0];
			$map['_logic'] = 'or';
		}
		$where = $map?$map:$where;

		$menuToolbarList = $menuToolbar_table
			->where($where)
			->limit($start, $limit)
			->order($order.' '.$by)->select();

		if(!$menuToolbarList){
			Log::write('无自定义菜单:'.$menuToolbar_table->getLastSql());
			Output::instance()->object([
				'code' => -1,
				'msg' => '暂无数据',
				'results' => []
			]);
			return;
		}
		Output::instance()->object([
			'code' => 0,
			'msg' => 'ok',
			'results' => $menuToolbarList
		]);
	}

	/**
	 * 删除自定义菜单
	 * @param $id /菜单id
	 */
	public function delMenuToolbar($id)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$menuToolbar_table = M('quan_menu_toolbar');
		$miyouquan_table = M('miyouquan');
		Session::switchCustomer($cid);

		$mentType = $menuToolbar_table->where('id ='.$id)->getField('type');
		if($mentType){
			Output::instance()->object([
				'code' => -1,
				'msg' => '系统菜单无法删除',
				'results' => []
			]);
			return;
		}
		//删除前通过另外一个接口进行判断是否存在正在使用此菜单的圈子
		M()->startTrans();
		$ret = $menuToolbar_table->where('id ='.$id)->save(['deleted' => 1]);
		if(!is_numeric($ret)){
			Log::write('删除自定义菜单失败:'.$menuToolbar_table->getLastSql());
			Output::instance()->object([
				'code' => -1,
				'msg' => '删除失败',
				'results' => []
			]);
			return;
		}

		//更新所有使用了此菜单的圈子配置
		$quanCnfList = $miyouquan_table->where(['cId' =>$cid])->field('id, config')->select();
		foreach($quanCnfList as $key => $val){
			$val['config'] = json_decode($val['config'], true);
			$bool = false;
			Log::write('bool:'.$bool.'aaa');
			foreach($val['config']['reveal']['menu'] as $k=> $v){
				if(in_array($id, $v) && !$v['type']){	//存在正在使用
					unset($val['config']['reveal']['menu'][$k]);
					sort($val['config']['reveal']['menu']);
					$bool = true;
				}
			}
			foreach($val['config']['reveal']['features'] as $featK=> $featV){
				if(in_array($id, $featV) && !$featV['type']){	//存在正在使用
					unset($val['config']['reveal']['features'][$featK]);
					sort($val['config']['reveal']['features']);
					$bool = true;
				}
			}
			if($bool){
				$config = json_encode($val['config']);
				$updateRet = $miyouquan_table->where(['id' => $val['id']])->save(['config' => $config]);
				if(!is_numeric($updateRet)){
					M()->rollback();
					Output::instance()->object([
						'code' => -1,
						'msg' => '删除失败',
						'results' => []
					]);
				}
			}
		}
		M()->commit();
		Output::instance()->object([
			'code' => 0,
			'msg' => 'ok',
			'results' => []
		]);
	}

	/**
	 * 判断菜单是否与现有的圈子存在关联,
	 * @param $id /菜单id
	 */
	public function beforeDelMenuToolbar($id)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miyouquan_table = M('miyouquan');
		Session::switchCustomer($cid);

		$quanCnfList = $miyouquan_table->where(['cId' =>$cid])->field('config')->select();
		foreach($quanCnfList as $key => $val){
			$val = json_decode($val['config'], true);
			foreach($val['config']['reveal']['menu'] as $k=> $v) {
				if (in_array($id, $v)) {    //存在正在使用
					if (in_array($id, $v)) {    //存在正在使用
						Output::instance()->object([
							'code' => -1,
							'msg' => '存在正在使用的圈子',
							'results' => []
						]);
						return;
						break;
					}
				}
			}
			foreach($val['config']['reveal']['features'] as $featK=> $featV){
				if(in_array($id, $featV)){	//存在正在使用
					Output::instance()->object([
						'code' => -1,
						'msg' => '存在正在使用的圈子',
						'results' => []
					]);
					return;
					break;
				}
			}

		}
		Output::instance()->object([
			'code' => 0,
			'msg' => 'ok',
			'results' => []
		]);
	}

    /**
     * 搜索某位好友相关下的好友列表
     * @param
     */
    public function friendsList($uid,$qid,$search=null,$start=0,$limit=10,$excel=null,$register='',$startTime='',$endTime='',$all='')
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        Session::switchCustomer($cid);
        if ($all) {
            $quserlist = $this->getQuserChildList($uid,$qid,$cid);
        }else {
            $quserlist = '';
        }
        $param = new stdClass();
        $param->uid = $uid;
        $param->qid = $qid;
        $param->search = $search;
        $param->excel = $excel;
        $param->start = $start;
        $param->limit = $limit;
        $param->startTime = $startTime;
        $param->endTime = $endTime;
        $param->all = $all;
        $param->uids = $quserlist;
        $param->register = $register;
        Module::callModule("community",NULL,"friendsList",$param);
    }

    public function StatisData($cid, $qid, $uid, $type){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $mimall_user = M('mimall_user');
        $mishare_from = M('mishare_from');
        $miu_statistics = M('miu_statistics');
        $quan_user = M('quan_user');
        $salesource_statistics = M('salesource_statistics');
        Session::switchCustomer($cid);

        if($type == 1){
            $where_friends['mi.miUid'] = $uid;
            $where_friends['mi.refereeUid'] = $uid;
            $where_friends['mi.preRefereeUid'] = $uid;
            $where_friends['_logic'] = "OR";
            $where_friend["_complex"] = $where_friends;
            $where_friend["mi.qId"] = $qid;
            $where_friend["mi.uId"] = array('neq', $uid);
            $where_friend["mi.cId"] = $cid;
            $friendCount = $mimall_user->alias("mi")
                ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
                ->where($where_friend)
                ->count();
            $where_friend['_string'] = "mi.uId = mi.miUid";
            $miuCount = $mimall_user->alias("mi")
                ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$qid." and qu.deleted=0")
                ->where($where_friend)
                ->count();
            $shareInfo = $mishare_from->where(['cid'=>$cid, 'uId'=>$uid])->field("count(*) as shareCount,sum(viewCount) as sharePv,sum(viewUv) as shareUv")->find();
            $orderInfo = $miu_statistics->where(['cid'=>$cid, 'uid'=>$uid])->field("formOrderCount,formOrderPrice,buyOrderCount,buyOrderPrice,pointOrderCount,pointOrderPoint")->find();
        }elseif ($type == 2) {
            $where_friend["mi.qId"] = $qid;
            $where_friend["mi.uId"] = array('neq', $uid);
            $where_friend["mi.cId"] = $cid;
            $where_friend['mi.saleSource'] = $uid;
            $friendCount = $mimall_user->alias("mi")
                ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =" . $qid . " and qu.deleted=0")
                ->where($where_friend)
                ->count();
            $saleSource_where['a.saleSource'] = array('eq', $uid);
            $saleSource_where['a.cid'] = array('eq', $cid);
            $miuCount = $quan_user->alias('a')->where($saleSource_where)->join('wx_miyouquan as b on a.qid=b.id')->count();
            $shareInfo = $mishare_from->where(['cid' => $cid, 'saleSourceUid' => $uid])->field("count(*) as shareCount,sum(viewCount) as sharePv,sum(viewUv) as shareUv")->find();
            $orderInfo = $salesource_statistics->where(['cid' => $cid, 'uid' => $uid])->field("formOrderCount,formOrderPrice,buyOrderCount,buyOrderPrice,pointOrderCount,pointOrderPoint")->find();
        }
        $data['friendCount'] = $friendCount;
        $data['miuCount'] = $miuCount;
        $data['shareCount'] = $shareInfo['shareCount'];
        $data['sharePv'] = $shareInfo['sharePv'];
        $data['shareUv'] = $shareInfo['shareUv'];
        $data['formOrderCount'] = $orderInfo['formOrderCount'];
        $data['formOrderPrice'] = $orderInfo['formOrderPrice'];
        $data['buyOrderCount'] = $orderInfo['buyOrderCount'];
        $data['buyOrderPrice'] = $orderInfo['buyOrderPrice'];
        $data['pointOrderCount'] = $orderInfo['pointOrderCount'];
        $data['pointOrderPoint'] = $orderInfo['pointOrderPoint'];
        return $data;
    }

    /*
     * 获取用户以及所有下级所有信息
     * @param  $rootId 查询商家id
     * @param  $quanId 密友圈id
     * @param  $cid 平台id
//     * @param  $extra 附加筛选条件
//     * @param  $start 开始值
//     * @param  $limit 偏移量
     */
    public function getQuserChildList($rootId,$quanId,$cid,$extra='',$start=0,$limit=10)
    {
        $sql = "select getQuserChildList($rootId,$quanId,$cid)";
        $quserChildList= M()->query($sql);
        //计算去除多余字符串
        $strlen = strlen($rootId) + 3;
        $quserlist = substr($quserChildList[0]['getQuserChildList('.$rootId.",".$quanId.",".$cid.')'],$strlen);
//        $quserlistArr = explode(',',$$quserlist);
//        $total = count($quserlistArr);
//        $quserlistArr = array_slice($quserlistArr,$start,$limit);
//        $quserlist =  implode(',',$quserlistArr);
//        $return['quserlist'] = $quserlist;
//        $return['total'] = $total;
        return $quserlist;
}


     public function operateRegisterData($id = '', $name, $icon, $descript, $type, $must)
     {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $registerDataModel = D('QuanRegisterData', 'Model');

        $res = $registerDataModel->operateRegisterData($id, $name, $icon, $descript, $type, $must);

        if ($res == 'default') {
            Output::instance()->object([
                'code' => 1,
                'msg' => '默认项不可修改'
            ]);
            return;
        }

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok',
                'id' => $res
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

     public function deleteRegisterDataById($id)
     {
         $retVal = Session::init();
         if (!$retVal) {
             Output::instance()->resultCode(code_access_denied);
             return;
         }
        $registerDataModel = D('QuanRegisterData', 'Model');

        $res = $registerDataModel->deleteRegisterDataById($id);

        if ($res == 'default') {
            Output::instance()->object([
                'code' => 1,
                'msg' => '默认项不可删除'
            ]);
            return;
        }

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok',
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    public function registerDataList($start, $limit, $type = 0)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $registerDataModel = D('QuanRegisterData', 'Model');

        $res = $registerDataModel->registerDataList($start, $limit, $type);

        Output::instance()->object($res);
    }

    /**
     * 等级添加白名单
     * @param $rankId  等级id
     * @param $phone    手机号
     */
    public function addWhiteList($qid,$rankId,$phone){

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $whiteModel = M("rank_white_list");
        $rankModel = M("miyouquan_setting_rank");
        Session::switchCustomer($cid);
        $quanRankId = $rankModel->where(['qid' => $qid])->getField('id',true);
        $quanRankId = implode(',',$quanRankId);
        $where['rankId'] = array('in', $quanRankId);
        $where['phone'] = array('eq', $phone);
        $arr = $whiteModel->where($where)->find();
        if(!empty($arr)){
            $out['code'] = 1;
            $out['msg'] = '该号码已存在白名单';
            Output::instance()->object($out);
            return;
        }

        $data['rankId'] = $rankId;
        $data['phone'] = $phone;
        $data['status'] = 0;
        $data['createTime'] = date('Y-m-d H:i:s');
        $result = $whiteModel->add($data);
        $fullName = Session::$user['fullName'];
        $rankName = $rankModel->where(['id' => $rankId])->getField('rankName');
        R('Log/add',array('marketing','233','营销圈',op_add,$whiteModel->getLastSql(),$fullName.'将手机号'.$phone.'添加到'.$rankName .'等级的白名单'));
        if($result){
            $out['code'] = 0;
            $out['msg'] = '添加成功';
            Output::instance()->object($out);
            return;
        }else{
            $out['code'] = 1;
            $out['msg'] = '添加失败';
            Output::instance()->object($out);
            return;
        }
    }

    /**
     * 删除白名单手机号
     * @param $id       删除白名单id
     * @param $rankId   等级id
     * @param $phone    手机号
     */
    public function deleteWhiteList($id,$rankId,$phone){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $whiteModel = M("rank_white_list");
        $rankModel = M("miyouquan_setting_rank");
        Session::switchCustomer($cid);
        $result = $whiteModel->where(['id' => $id])->delete();
        $fullName = Session::$user['fullName'];
        $rankName = $rankModel->where(['id' => $rankId])->getField('rankName');
        R('Log/add',array('marketing','233','营销圈',op_add,$whiteModel->getLastSql(),$fullName.'将手机号'.$phone.'从'.$rankName .'等级的白名单里删除'));
        if($result){
            $out['code'] = 0;
            $out['msg'] = '删除成功';
            Output::instance()->object($out);
            return;
        }else{
            $out['code'] = 0;
            $out['msg'] = '删除失败';
            Output::instance()->object($out);
            return;
        }
    }

    /**
     * 白名单列表
     * @param $rankId   等级id
     * @param $qid      圈id
     */
    public function whiteList($rankId, $qid)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $whiteModel = M("rank_white_list");
        $quserModel = M("quan_user");
        Session::switchCustomer($cid);
        $whiteInfo = $whiteModel->alias('a')->where(['a.rankId' => $rankId])->select();
        foreach ($whiteInfo as $key => $value) {
            if ($value['status'] == 1) {
                $whiteInfo[$key]['registered'] = $quserModel->where(['phone' => $value['phone'], 'qid' => $qid])->getField('createTime');
            }
        }

        $out['code'] = 0;
        $out['msg'] = '获取数据成功';
        $out['data'] = $whiteInfo;
        Output::instance()->object($out);
        return;
    }
}
